﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using Microsoft.SharePoint;
using System.Web.Caching;

namespace TNO.Education.SearchResultBox
{
    public partial class SearchResultBoxUserControl : UserControl
    {
        protected string BaseUrl
        {
            get
            {
                int endIndex = SPContext.Current.Web.Url.IndexOf("?");
                if (endIndex != -1)
                    return SPContext.Current.ListItemServerRelativeUrl.Substring(0, endIndex + 1);
                else
                    return SPContext.Current.ListItemServerRelativeUrl;
            }
        }

        private string ConnectionString = System.Configuration.ConfigurationManager.
                ConnectionStrings["TuyenSinhConnectionString"].ConnectionString;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.Literal1.Text = (this.Parent as WebPart).Title;
                TxtTraCuu.Attributes.Add("onkeypress", "var kCode = event.keyCode; if(kCode==13) {var butSearch; for(i=0;i<document.getElementsByTagName(\"INPUT\").length;i++){var strvalue = document.getElementsByTagName(\"INPUT\")[i].attributes[\"id\"].value; if(strvalue.indexOf(\"BtnSearch\")!=-1) {butSearch = document.getElementById(strvalue); } } butSearch.click();}");
            }

            pnlTruongCoDiem.Controls.Clear();
            if (SearchResultBox._displayUniversity)
            {
                DataTable tableCategory;
                object obj = HttpContext.Current.Cache[this.BaseUrl + "NewUniversities"];
                lock (this)
                {
                    if (obj == null)
                    {
                        tableCategory = GetUniversityList();
                        HttpContext.Current.Cache.Add(this.BaseUrl + "NewUniversities", tableCategory, null, DateTime.Now.AddSeconds(30), TimeSpan.Zero, CacheItemPriority.Default, null);
                    }
                    else
                    {
                        tableCategory = (DataTable)obj;
                    }
                }

                if (tableCategory.Rows.Count > 0)
                {
                    using (HtmlHelper htmlHelper = new HtmlHelper())
                    {
                        using (htmlHelper.RenderTag(HtmlTag.Div))
                        {
                            htmlHelper.AddStyle("font-weight: bolder");
                            using (htmlHelper.RenderTag(HtmlTag.Div))
                            {
                                htmlHelper.WriteLine("Các trường mới có điểm:");
                                using (htmlHelper.RenderTag(HtmlTag.Span))
                                {
                                    htmlHelper.AddAttribute("alt", "diem thi moi");
                                    htmlHelper.AddAttribute("src", "/_layouts/images/TNO.Education/New.gif");
                                    htmlHelper.WriteLine(HtmlTag.Img);
                                }
                            }
                            using (htmlHelper.RenderTag(HtmlTag.Div))
                            {
                                htmlHelper.AddStyle("display: inline");
                                using (htmlHelper.RenderTag(HtmlTag.Ul))
                                {
                                    for (int i = 0; i < tableCategory.Rows.Count; i++)
                                    {
                                        using (htmlHelper.RenderTag(HtmlTag.Li))
                                        {
                                            htmlHelper.AddAttribute("href", SearchResultBox._url + "?u=" + tableCategory.Rows[i][Fields.University.Id].ToString());
                                            htmlHelper.WriteLine(HtmlTag.A, tableCategory.Rows[i][Fields.University.Title].ToString());
                                        }
                                    }
                                }
                            }
                        }

                        pnlTruongCoDiem.Controls.Add(new LiteralControl(htmlHelper.ToString()));
                    }
                }
            }
        }

        protected void BtnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                if (TxtTraCuu.Text.Trim().Length == 0)
                {
                    throw new Exception("Bạn chưa nhập số báo danh");
                }
                else
                {
                    string SBD = TxtTraCuu.Text.Trim();
                    Page.Response.Redirect(SearchResultBox._url + "?SBD=" + SBD);
                }
            }
            catch (Exception Error)
            {
                lbl_error.Text = Error.Message;
            }
        }

        private DataTable GetUniversityList()
        {
            DataTable table = new DataTable();
            string sqlQuery = @"
                SELECT TOP 5 RTRIM(ID) AS ID, Title FROM TruongDaiHoc
                WHERE RTRIM(ID) IN (SELECT DISTINCT ID_Truong FROM ThiSinh_DaiHoc)
                ORDER BY CreatedDate DESC, Title";
            using (SqlConnection conn = new SqlConnection(ConnectionString))
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand(sqlQuery, conn))
                {
                    using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
                    {
                        adapter.Fill(table);
                    }
                }
            }

            return table;
        }

    }
}
